﻿using Callisto.Controls;
using GoogleMusicAPI;
using MetaMusicNet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WinRTXamlToolkit.Controls;
using WinRTXamlToolkit.Controls.DataVisualization.Charting;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace MetaMusicMetro
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    
    
    public sealed partial class HomePage : MetaMusicMetro.Common.LayoutAwarePage
    {
        private const string GoogleClientID = "285371747012.apps.googleusercontent.com";
        private const string GoogleCallbackUrl = "urn:ietf:wg:oauth:2.0:oob";
        private SettingsFlyout sf;
        private TextBox emailBox;
        private PasswordBox passwordBox;
        private ProgressBar loginBar;

        
        public HomePage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            
            Random _random = new Random();
            List<NameValueItem> items = new List<NameValueItem>();
            items.Add(new NameValueItem { Name = "Test1", Value = _random.Next(10, 100) });
            items.Add(new NameValueItem { Name = "Test2", Value = _random.Next(10, 100) });
            items.Add(new NameValueItem { Name = "Test3", Value = _random.Next(10, 100) });
            items.Add(new NameValueItem { Name = "Test4", Value = _random.Next(10, 100) });
            items.Add(new NameValueItem { Name = "Test5", Value = _random.Next(10, 100) });
            (pieChart.Series[0] as PieSeries).ItemsSource = items;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }
        private async void loginSubmit_Click(object sender, RoutedEventArgs e)
        {
            
            /*String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(GoogleClientID) + "&redirect_uri=" + Uri.EscapeDataString(GoogleCallbackUrl) + "&response_type=code&scope=" + Uri.EscapeDataString("http://picasaweb.google.com/data");

            System.Uri StartUri = new Uri(GoogleURL);
            // When using the desktop flow, the success code is displayed in the html title of this end uri
            System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

            //DebugPrint("Navigating to: " + GoogleURL);

            WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                                    WebAuthenticationOptions.None,
                                                    StartUri,
                                                    EndUri);
            
            if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                OutputToken(WebAuthenticationResult.ResponseData.ToString());
            }
            else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
            }
            else
            {
                OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
            }
            OAUTH METHOD> CANT ACCESS GOOGLE MUSIC*/

            createLoginFlyout();

            

        }
        /*
         *  private void OutputToken(string p)
        {
            API api = (API)Application.Current.Resources["googleMusicApi"];
            if (!p.Contains("Error"))
            {
                api.OnLoginComplete = new EventHandler(loginComplete);
                api.Login(p);
            }
        }*/

        private void createLoginFlyout()
        {
            sf = new SettingsFlyout();
            sf.FlyoutWidth = SettingsFlyout.SettingsFlyoutWidth.Narrow;
            StackPanel sp = new StackPanel(){Orientation=Orientation.Vertical};

            loginBar = new ProgressBar() { IsIndeterminate = true, Visibility=Visibility.Collapsed };
            sp.Children.Add(loginBar);
           
            #region Email
            sp.Children.Add(new TextBlock() { Text = "Email", Style = this.Resources["HeaderStyle"] as Style });
            emailBox =new TextBox();
            sp.Children.Add(emailBox);
            #endregion

            #region Password
            sp.Children.Add(new TextBlock() { Text = "Password", Style = this.Resources["HeaderStyle"] as Style });
            passwordBox = new PasswordBox();
            sp.Children.Add(passwordBox);
            #endregion

            #region Button
            Button b = new Button();
            b.Content = "Login";
            b.Click+=login_Click;
            b.Margin = new Thickness(0,20,0,0);
            #endregion

            sp.Children.Add(b);
            sp.Width = 300;
            sf.ContentBackgroundBrush = new SolidColorBrush(Color.FromArgb(0,0,0,0));
            sf.Content = sp;
            sf.HeaderText = "Google Credentials";
            sf.IsOpen = true;
       
            
        }

        private void login_Click(object sender, RoutedEventArgs e)
        {
            loginBar.Visibility = Visibility.Visible;
            API api = (API)Application.Current.Resources["googleMusicApi"];
            api.Login(emailBox.Text, passwordBox.Password);
            api.OnLoginComplete = new EventHandler(loginComplete);
        }

        private async void loginComplete(object sender, EventArgs e)
        {
         
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, ()=>
            {
                loginButton.Content = "Logged In"; 
                loginBar.Visibility = Visibility.Collapsed;
                sf.IsOpen = false;
            });

           
        }

        private void load_Click(object sender, RoutedEventArgs e)
        {
            API api = Application.Current.Resources["googleMusicApi"] as API;
            api.OnGetAllSongsComplete += loadSongsComplete;
            api.GetAllSongs();
        }

        private async void loadSongsComplete(List<GoogleMusicSong> songList)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    MusicCollection collection = Application.Current.Resources["googleMusicSongs"] as MusicCollection;
                    collection.addSongs(songList);
                    refeshGraphs();
                });
        }

        private void refeshGraphs()
        {
            Dictionary<string, int> genreCounts = (Application.Current.Resources["googleMusicSongs"] as MusicCollection).genreCounts;
            List<NameValueItem> items = new List<NameValueItem>();
            foreach (string s in genreCounts.Keys)
            {
                items.Add(new NameValueItem() { Name = s, Value = genreCounts[s] });
            }

            (pieChart.Series[0] as PieSeries).ItemsSource = items;

        }


    }
    public class NameValueItem
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
}
